/*
 * HSM Proxy Project.
 * Copyright (C) 2013 FedICT.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version
 * 3.0 as published by the Free Software Foundation.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, see 
 * http://www.gnu.org/licenses/.
 */

package be.fedict.hsm.ws.impl;

import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.Set;

import javax.ejb.EJB;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import javax.xml.namespace.QName;
import javax.xml.ws.ProtocolException;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import be.fedict.hsm.model.security.SecurityAuditGeneratorBean;
import be.fedict.hsm.model.security.SecurityFunction;

@SecurityFunction("SF.I&A.1")
public class JAASSOAPHandler implements SOAPHandler<SOAPMessageContext> {

	private static final Log LOG = LogFactory.getLog(JAASSOAPHandler.class);

	private static final String LOGIN_CONTEXT_ATTRIBUTE = JAASSOAPHandler.class
			.getName() + ".loginContext";

	@EJB
	private SecurityAuditGeneratorBean securityAuditGeneratorBean;

	@Override
	public boolean handleMessage(SOAPMessageContext context) {
		Boolean outboundProperty = (Boolean) context
				.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
		if (false == outboundProperty) {
			try {
				login(context);
			} catch (Exception e) {
				this.securityAuditGeneratorBean.webServiceAuthenticationError();
				throw new ProtocolException("JAAS login error: "
						+ e.getMessage(), e);
			}
		} else {
			try {
				logout(context);
			} catch (LoginException e) {
				this.securityAuditGeneratorBean.webServiceAuthenticationError();
				throw new ProtocolException("JAAS logout error: "
						+ e.getMessage(), e);
			}
		}
		return true;
	}

	private void logout(SOAPMessageContext context) throws LoginException {
		LoginContext loginContext = (LoginContext) context
				.remove(LOGIN_CONTEXT_ATTRIBUTE);
		if (null == loginContext) {
			return;
		}
		loginContext.logout();
	}

	private void login(SOAPMessageContext context) throws LoginException,
			CertificateEncodingException {
		X509Certificate certificate = WSSecuritySOAPHandler
				.getAuthenticatedCertificate(context);
		byte[] encodedCertificate = certificate.getEncoded();
		NamePasswordCallbackHandler usernamePasswordHandler = new NamePasswordCallbackHandler(
				encodedCertificate);
		LoginContext loginContext = new LoginContext(
				ApplicationClientSecurityDomain.NAME, usernamePasswordHandler);
		context.put(LOGIN_CONTEXT_ATTRIBUTE, loginContext);
		loginContext.login();
	}

	@Override
	public boolean handleFault(SOAPMessageContext context) {
		Boolean outboundProperty = (Boolean) context
				.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
		if (outboundProperty) {
			try {
				logout(context);
			} catch (LoginException e) {
				this.securityAuditGeneratorBean.webServiceAuthenticationError();
				throw new ProtocolException("JAAS logout error: "
						+ e.getMessage(), e);
			}
		}
		return true;
	}

	@Override
	public void close(MessageContext context) {
		LOG.debug("close");
	}

	@Override
	public Set<QName> getHeaders() {
		return null;
	}
}
